package de.schnocklake.android.soap;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.params.HttpParams;




public class CustomSSLSocketFactory implements SocketFactory, LayeredSocketFactory {
	private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory ();
	
	
	public CustomSSLSocketFactory()
	    {
	    try
	        {
	        SSLContext context = SSLContext.getInstance ("TLS");
	        TrustManager[] tm = new TrustManager[] { new _FakeX509TrustManager() };
	        context.init (null, tm, new SecureRandom ());
	        FACTORY = context.getSocketFactory ();
	        }
	    catch (Exception e)
	        {
	        e.printStackTrace();
	        }
	    }
	
	
	@Override
	public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
			HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
		if (sock == null) {
			Socket socket = createSocket();
			socket.connect(new InetSocketAddress(host, port));
			return socket;
		} else {
			sock.connect(new InetSocketAddress(host, port));
			return sock;
		}
	}

	@Override
	public Socket createSocket() throws IOException {
		return FACTORY.createSocket();
	}

	@Override
	public boolean isSecure(Socket sock) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		return true;
	}


	@Override
	public Socket createSocket(Socket sock, String host, int port, boolean autoClose) throws IOException,
			UnknownHostException {
//		if (sock == null) {
			Socket socket = createSocket();
			socket.connect(new InetSocketAddress(host, port));
			return socket;
//		} else {
//			sock.connect(new InetSocketAddress(host, port));
//			return sock;
//		}

	}
	
	
	public static class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager {
		private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		public boolean isClientTrusted(X509Certificate[] chain) {
			return (true);
		}

		public boolean isServerTrusted(X509Certificate[] chain) {
			return (true);
		}

		public X509Certificate[] getAcceptedIssuers() {
			return (_AcceptedIssuers);
		}
	}
	

}
